package com.wkf.truck.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wkf.truck.common.R;
import com.wkf.truck.dto.UserDto;
import com.wkf.truck.model.User;
import com.wkf.truck.dao.UserDao;
import com.wkf.truck.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lxb
 * @since 2021-02-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Resource
    private UserDao userDao;

    @Override
    public R register(UserDto userDto) {

        String phone = getPhone(userDto);

        if (phone == null) {
            return R.error("获取手机号错误");
        }
        User user = new User();
        user.setUsername(userDto.getUsername());
        user.setRoleId(userDto.getRoleCode());
        user.setPhone(phone);
        user.setOpenId(userDto.getOpenId());

        userDao.insert(user);
        return R.ok();
    }

    public String getPhone(UserDto userDto) {
        String coding = "UTF-8";
        String result = null;
        try {
            result = decryptS5(userDto.getEncryptedData(), coding, userDto.getSessionKey(), userDto.getIv());
        } catch (Exception e) {
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(result);
        String phoneNumber = jsonObject.getString("phoneNumber");

        return phoneNumber;
    }

    public String decryptS5(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] raw = decoder.decodeBuffer(sKey);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] myendicod = decoder.decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(myendicod);
            String originalString = new String(original, encodingFormat);
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }
}
